
package com.scs.application.modules.order.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.BeanValidators;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.order.entity.PurchaseOrderItem;
import com.scs.application.modules.order.request.PurchaseOrderItemQueryRequest;
import com.scs.application.modules.order.service.PurchaseOrderItemService;
import lombok.AllArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 采购订单明细 controller
 *
 */
@AllArgsConstructor
@RestController
@RequestMapping("/order/purchase_order_items")
public class PurchaseOrderItemController extends CrudController<PurchaseOrderItem, String, PurchaseOrderItemService> implements ImAndExAbleController<PurchaseOrderItemQueryRequest> {

    @PostMapping
    public CommonResult add(@RequestBody @Valid PurchaseOrderItem entity) {
        service.add(entity);
        return CommonResult.ok("新增成功", entity);
    }

    @Override
    @PutMapping
    public CommonResult update(@RequestBody @Valid PurchaseOrderItem entity) {

        entity.setQty(entity.getOrderQty());
        entity.setSubtotalAmount(entity.getOrderQty() * entity.getPrice());

        service.update(entity);
        return CommonResult.ok("保存成功", entity);
    }

    @GetMapping("/page")
    public PageResult page(PurchaseOrderItemQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(PurchaseOrderItemQueryRequest request) {
        if (StringUtils.isBlank(request.getPoId())) {
            return CommonResult.error();
        }
        List<PurchaseOrderItem> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }


    @Override
    @DeleteMapping("/{id}")
    public CommonResult deleteById(@PathVariable("id") String id) {
        service.delete(id);
        return CommonResult.ok("删除成功");
    }

    @PutMapping("/batch_save")
    public CommonResult batchSave(@Valid @RequestBody List<PurchaseOrderItem> children) {

        children.forEach(item -> {
            item.setSubtotalAmount(item.getQty() * item.getPrice());
        });

        Assert.notEmpty(children, "至少有一条");
        BeanValidators.validateListWithException(validator, children);
        service.batchSave(children);
        return CommonResult.ok("保存成功");
    }
}
